import java.time.Period;
import java.time.temporal.ValueRange;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-05-09
 * Time: 22:40
 */

public class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int x: asteroids) {
            boolean alive = true; // 标记 x 是否还存活
            // 只有新的行星向左, 栈顶向右才有可能发生碰撞
            while (alive && x < 0 && !stack.isEmpty() && stack.peek() > 0){
                // 如果新的行星小, 那么及时标记为不存活, 方便后来就不添加了
                alive = (-x) > stack.peek();
                // 注意这里面要加上 == , 因为只要两个大小相同, 两个都会毁灭
                if ((-x) >= stack.peek()){
                    stack.pop();
                }
            }
            if (alive){
                stack.push(x);
            }
        }
        int size = stack.size();
        int[] ans = new int[size];
        for (int i = size - 1; i >= 0; i--) {
            ans[i] = stack.pop();
        }
        return ans;
    }
}
